<template>
  <div>
    <el-breadcrumb
      separator-class="el-icon-arrow-right"
      class="breadcrumb-base"
      style="line-height: 30px"
    >
      <el-breadcrumb-item :to="{ path: '/institution/report-templates' }">
        <i class="el-icon-document-copy"></i>
        报告模板
      </el-breadcrumb-item>
      <el-breadcrumb-item> 报告编辑 </el-breadcrumb-item>
    </el-breadcrumb>

    <div class="container-inner">
      <div class="container-left">
        <el-row style="height: 40px" type="flex" align="middle">
          <!--报告模板保存-->
          <el-button @click="templateSave" type="primary" size="mini"
            >保存
          </el-button>
          <!--恢复至编辑前-->
          <el-button @click="templateRecover" type="primary" size="mini"
            >恢复
          </el-button>
          <!--新增组件-->
          <el-button @click="componentDialogOpen(-1)" type="primary" size="mini"
            >新增
          </el-button>
          <!--预览报告模板-->
          <el-button @click="templatePreview" type="primary" size="mini"
            >预览
          </el-button>
          <!--重置回默认样式-->
          <el-button @click="templateDefault" type="primary" size="mini"
            >默认
          </el-button>

          <el-button @click="settingDialogOpen" type="primary" size="mini"
            >模板设置
          </el-button>
        </el-row>
        <el-row style="height: 40px" type="flex" align="middle">
          <el-switch
            v-model="isShowSign"
            active-color="#13ce66"
            inactive-color="#ff4949"
            inactive-text="显示标识符"
          >
          </el-switch>
        </el-row>
        <el-row>
          <el-collapse v-model="componentsCategoryActive">
            <el-collapse-item
              v-for="item in componentsCategory.info"
              :title="item.label"
              :name="item.key"
              :key="item.key"
            >
              <el-row
                v-for="(t, index) in componentsCategory[item.key]"
                :key="index"
                style="height: 30px"
                type="flex"
                align="middle"
              >
                <span v-if="isShowSign">{{ t.i }}</span>
                <span v-else>{{ t.name }}</span>
                <el-button
                  @click="componentDialogOpen(t.index)"
                  type="text"
                  size="mini"
                  style="margin-left: 10px"
                  >编辑
                </el-button>
                <el-button
                  @click="componentClone(t.index)"
                  type="text"
                  size="mini"
                  style="margin-left: 10px"
                  >复制
                </el-button>
                <el-button
                  @click="componentRemove(t.index)"
                  type="text"
                  size="mini"
                  style="color: red"
                  >移除
                </el-button>
              </el-row>
            </el-collapse-item>
          </el-collapse>
        </el-row>
      </div>
      <div class="container-right">
        <el-row class="text-mini">
          <span>日期</span>
        </el-row>
        <!-- Header -->
        <el-form ref="templatesInfo" :model="templatesInfo" label-width="100px">
          <div style="margin-top: 20px">
            <el-row style="min-height: 60px; margin-bottom: 20px">
              <el-col :span="18" :offset="3" class="template">
                <el-upload
                  class=""
                  :action="templateImageUploadUrl"
                  ref="addItemDataUpload"
                  :on-success="handleAvatarSuccess"
                  :show-file-list="false"
                  :drag="true"
                >
                  <img
                    v-if="templatesInfo.infoImageUrl"
                    :src="templatesInfo.infoImageUrl"
                    style="width: 146px"
                    class="avatar"
                  />
                  <div v-else>请上传图片</div>
                </el-upload>
                <!-- <img :src="orgData.logoimgurl"
                                 style="height:60px;width:100%;" alt=""/> -->
              </el-col>
            </el-row>
            <el-row>
              <el-form-item label="医院名称">
                <el-input
                  v-model="templatesInfo.infoInstitutionName"
                  placeholder="请输入医院名称"
                  class="input-form"
                  size="mini"
                >
                </el-input>
              </el-form-item>
            </el-row>
            <el-row style="margin-top: 5px">
              <el-form-item label="报告标题">
                <el-input
                  v-model="templatesInfo.infoTitle"
                  placeholder="请输入报告标题"
                  class="input-form"
                  size="mini"
                >
                </el-input>
              </el-form-item>
            </el-row>
            <el-row style="margin-top: 5px">
              <el-form-item label="水印">
                <el-input
                  v-model="templatesInfo.infoWatermark"
                  placeholder="请输入水印内容"
                  class="input-form"
                  size="mini"
                >
                </el-input>
              </el-form-item>
            </el-row>
            <el-row style="margin-top: 5px">
              <el-col :span="10" :offset="18">
                <h4 style="color: rgb(217, 149, 148)">病理号:</h4>
              </el-col>
            </el-row>
          </div>

          <hr />

          <grid-layout
            id="custom-report"
            :layout.sync="componentList"
            :col-num="templatesInfo.settingsColNum"
            :row-height="28"
            :is-draggable="true"
            :is-resizable="true"
            :is-mirrored="false"
            :vertical-compact="true"
            :use-css-transforms="true"
            style="margin-top: 12px"
          >
            <grid-item
              v-for="(item, index) in componentList"
              :x="item.x"
              :y="item.y"
              :w="item.w"
              :h="item.h"
              :i="item.i"
              :key="index"
            >
              <el-tooltip
                :content="isShowSign ? item.i : item.name"
                placement="top"
                effect="dark"
              >
                <el-row
                  v-if="item.smallType === 'space'"
                  class="row-in-grid-item"
                ></el-row>

                <hr v-else-if="item.smallType === 'hr'" />

                <el-row
                  v-else-if="item.smallType === 'text'"
                  class="row-in-grid-item"
                >
                  <span :style="styleString(item.styleJson)">
                    {{ item.stringContent }}
                  </span>
                </el-row>

                <el-row
                  v-else-if="item.smallType === 'input'"
                  class="row-in-grid-item"
                >
                  <div :id="item.i" style="width: 100%; height: 100%">
                    <el-input
                      v-if="item.isInputArea"
                      type="textarea"
                      v-model="item.value"
                      :autosize="{
                        minRows: 1,
                        maxRows: parseInt((item.h * 5) / 3, 10),
                      }"
                      :placeholder="item.placeholder"
                      :style="styleString(item.styleJson)"
                      size="mini"
                    >
                    </el-input>
                    <el-input
                      v-else
                      v-model="item.value"
                      :placeholder="item.placeholder"
                      :style="styleString(item.styleJson)"
                      size="mini"
                    >
                    </el-input>
                  </div>
                </el-row>

                <el-row
                  v-else-if="item.smallType === 'selection'"
                  class="row-in-grid-item"
                >
                  <div :id="item.i" style="width: 100%; height: 100%">
                    <el-select
                      v-model="item.value"
                      :placeholder="item.placeholder"
                      :style="styleString(item.styleJson)"
                      size="mini"
                    >
                      <el-option
                        v-for="(t, index) in item.selectDataJson"
                        :key="index"
                        :label="t"
                        :value="t"
                      >
                      </el-option>
                    </el-select>
                  </div>
                </el-row>

                <el-row
                  v-else-if="item.smallType === 'special'"
                  class="row-in-grid-item"
                >
                  <!--病理图像判断-->
                  <div
                    v-if="item.i === 'special_normal_pathologyFiles'"
                    style="width: 100%; height: 100%"
                  >
                    <span style="float: left">{{ item.stringContent }}</span>
                  </div>
                  <!--签名图像-->
                  <div v-else-if="item.i === 'special_base_reportDoctor'">
                    <span>{{ item.stringContent }}</span>
                  </div>
                  <!--特殊检查-导入-->
                  <div
                    v-else-if="item.i === 'special_normal_import'"
                    style="margin-left: 10px"
                  >
                    <el-button size="mini" type="text">
                      {{ item.stringContent }}
                    </el-button>
                  </div>
                  <div
                    v-else-if="item.i === 'special_clearable_microFingings'"
                    style="margin-left: 10px"
                  >
                    <el-button size="mini" type="text">
                      {{ item.stringContent }}
                    </el-button>
                  </div>
                  <div
                    v-else-if="item.i === 'special_clearable_specialCheck'"
                    style="margin-left: 10px"
                  >
                    <el-button size="mini" type="text">
                      {{ item.stringContent }}
                    </el-button>
                  </div>
                  <div
                    v-else-if="item.i === 'special_clearable_diagnose'"
                    style="margin-left: 10px"
                  >
                    <el-button size="mini" type="text">
                      {{ item.stringContent }}
                    </el-button>
                  </div>
                </el-row>
              </el-tooltip>
            </grid-item>
          </grid-layout>
          <el-row>
            <el-input
              type="textarea"
              :autosize="{ minRows: 1, maxRows: 5 }"
              style="font-size: 16px"
              v-model="templatesInfo.infoRemark"
              size="mini"
              placeholder="请输入备注"
            >
            </el-input>
          </el-row>
        </el-form>
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      title="模板设置"
      :visible.sync="settingDialog.visible"
      width="30%"
      center
    >
      <el-form
        ref="settingForm"
        :model="settingForm"
        label-width="120px"
        :rules="settingFormRules"
      >
        <el-form-item
          label="报告期限(天)"
          prop="settingsDeadline"
          class="row-padding-bottom"
        >
          <el-input
            v-model="settingForm.settingsDeadline"
            placeholder="请输入报告期限(天)"
            class="input-form"
            type="number"
            size="mini"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="标本类别"
          prop="settingsSpecimenCategory"
          class="row-padding-bottom"
        >
          <el-select
            v-model="settingForm.settingsSpecimenCategory"
            placeholder="请选择标本类别"
            class="picker-form"
            size="mini"
          >
            <el-option
              v-for="(data, index) in specimenCategoryList"
              :key="index"
              :label="data.name"
              :value="data.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="检查类型"
          prop="checkCategory"
          class="row-padding-bottom"
        >
          <el-select
            v-model="settingForm.checkCategory"
            placeholder="请选择检查类型"
            class="picker-form"
            size="mini"
          >
            <el-option
              v-for="(data, index) in checkCategoryList"
              :key="index"
              :label="data.name"
              :value="data.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="settingForm.settingsRemark"
            placeholder="请输入模板备注"
            class="input-form"
            size="mini"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="报告列数">
          <el-radio-group
            v-model="settingForm.settingsColNum"
            size="mini"
            class="radio-group"
          >
            <el-radio
              v-for="(t, index) in [12, 24]"
              :label="t"
              :key="index"
              size="mini"
              >{{ t }}列
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-row style="margin-top: 10px" type="flex" justify="end">
        <el-button @click="settingDialog.visible = false" size="mini"
          >取 消</el-button
        >
        <el-button @click="settingDialogSave" size="mini" type="primary"
          >确 定</el-button
        >
      </el-row>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :title="componentDialog.title"
      :visible.sync="componentDialog.visible"
      width="850px"
    >
      <el-form
        ref="componentForm"
        :model="componentForm"
        label-width="100px"
        :rules="componentFormRules"
      >
        <el-row>
          <el-form-item label="组件类型">
            <template>
              <el-radio-group
                v-model="componentForm.bigType"
                @change="componentFormBigTypeChanged"
                size="mini"
                :disabled="!componentDialog.isAddNew"
              >
                <el-radio label="custom" size="mini">自定义</el-radio>
                <el-radio label="base" size="mini">基本信息</el-radio>
                <el-radio label="normal" size="mini">常规病理</el-radio>
              </el-radio-group>
            </template>
          </el-form-item>
        </el-row>
        <el-row v-if="componentForm.bigType === 'custom'">
          <el-form-item label="自定义">
            <template>
              <el-radio-group
                v-model="componentForm.smallType"
                @change="componentFormSmallTypeChanged"
                :disabled="!componentDialog.isAddNew"
                size="mini"
              >
                <el-radio label="space" size="mini">空格</el-radio>
                <el-radio label="hr" size="mini">分隔线</el-radio>
                <el-radio label="text" size="mini">文本</el-radio>
                <el-radio label="input" size="mini">输入框</el-radio>
                <el-radio label="selection" size="mini">选择框</el-radio>
              </el-radio-group>
            </template>
          </el-form-item>
        </el-row>
        <el-row v-if="componentForm.bigType === 'base'">
          <el-form-item label="基本信息">
            <el-radio-group
              v-model="componentForm.smallTypeIndex"
              @change="componentFormSmallTypeIndexChanged"
              :disabled="!componentDialog.isAddNew"
              size="mini"
              class="radio-group"
            >
              <el-radio
                v-for="(t, index) in defaultBaseComponentList"
                :label="index"
                size="mini"
                :key="index"
              >
                {{ t.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row v-else-if="componentForm.bigType === 'normal'">
          <el-form-item label="常规病理">
            <el-radio-group
              v-model="componentForm.smallTypeIndex"
              @change="componentFormSmallTypeIndexChanged"
              :disabled="!componentDialog.isAddNew"
              size="mini"
              class="radio-group"
            >
              <el-radio
                v-for="(t, index) in defaultNormalDiagnoseComponentGroup"
                :label="index"
                size="mini"
                :key="index"
              >
                {{ t.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="标记名" prop="name">
            <el-input
              v-model="componentForm.name"
              :disabled="
                componentForm.bigType === 'normal' && componentDialog.isAddNew
              "
              placeholder="请输入标记名"
              size="mini"
            >
            </el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="标识符" prop="i">
            <el-input
              v-model="componentForm.i"
              :disabled="
                componentForm.bigType === 'base' ||
                componentForm.bigType === 'normal'
              "
              placeholder="请输入标识符"
              size="mini"
            >
            </el-input>
          </el-form-item>
        </el-row>
        <div v-if="componentForm.smallType === 'text'">
          <el-row>
            <el-form-item label="内容">
              <el-input
                v-model="componentForm.stringContent"
                :autosize="{ minRows: 1, maxRows: 5 }"
                placeholder="请输入文本内容"
                size="mini"
                type="textarea"
              >
              </el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="文本对齐模式">
              <el-radio-group
                v-model="componentForm.styleJson['text-align']"
                size="mini"
              >
                <el-radio label="left" size="mini">左对齐</el-radio>
                <el-radio label="center" size="mini">居中</el-radio>
                <el-radio label="right" size="mini">右对齐</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-row>
        </div>

        <div
          v-else-if="
            componentForm.smallType === 'input' ||
            componentForm.smallType === 'selection'
          "
        >
          <el-form-item
            label="输入框样式"
            v-if="componentForm.smallType === 'input'"
          >
            <el-radio-group v-model="componentForm.isInputArea" size="mini">
              <el-radio :label="false" size="mini">单行输入</el-radio>
              <el-radio :label="true" size="mini">多行输入</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="文本对齐模式">
            <el-radio-group
              v-model="componentForm.styleJson['text-align']"
              size="mini"
            >
              <el-radio label="left" size="mini">左对齐</el-radio>
              <el-radio label="center" size="mini">居中</el-radio>
              <el-radio label="right" size="mini">右对齐</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="提示内容">
            <el-input
              v-model="componentForm.placeholder"
              placeholder="请输入提示文本"
              size="mini"
            >
            </el-input>
          </el-form-item>
          <el-row
            v-if="componentForm.smallType === 'selection'"
            style="height: 40px; display: flex; align-items: center"
          >
            <el-button
              @click="componentFormSelectionAdd"
              size="mini"
              type="primary"
            >
              新增选项
            </el-button>
          </el-row>
          <el-row type="flex" justify="center">
            <el-table
              v-if="componentForm.smallType === 'selection'"
              :data="componentFormTable"
              border
              :header-cell-style="{
                'background-color': '#E6E9EF',
                color: '#777C7C',
                'font-weight': '400',
                'font-size': '15px',
                'border-right': '1px solid #ffffff',
              }"
              size="mini"
              style="max-width: 600px"
            >
              <el-table-column
                label="序号"
                prop="index"
                width="60"
                align="center"
              >
              </el-table-column>
              <el-table-column
                label="选项名"
                prop="name"
                width="250"
                align="center"
              >
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                    @click="componentFormTableEdit(scope['row'])"
                    type="text"
                    size="small"
                  >
                    编辑
                  </el-button>
                  <el-button
                    @click="componentFormTableRemove(scope['row'].index)"
                    type="text"
                    size="small"
                  >
                    <span style="color: red">删除</span>
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </div>
        <el-row style="margin-top: 10px" type="flex" justify="end">
          <el-button @click="componentDialogSubmit" size="mini" type="primary"
            >提交
          </el-button>
          <el-button @click="componentDialog.visible = false" size="mini"
            >取消
          </el-button>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import VueGridLayout from 'vue-grid-layout';
import _ from 'lodash';
import { vxRule } from '../../libs/validator';

const defaultBaseComponents = [
  {
    name: '姓名：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_name',
    weight: 0.25,
    h: 1,
  },
  {
    name: '性别：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_sexName',
    weight: 0.25,
    h: 1,
  },
  {
    name: '年龄：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_ageAll',
    weight: 0.25,
    h: 1,
  },
  {
    name: '身份证号：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_cardId',
    weight: 0.25,
    h: 1,
  },
  {
    name: '住院号：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_hospitalizedNo',
    weight: 0.25,
    h: 1,
  },
  {
    name: '门诊号：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_patientNo',
    weight: 0.25,
    h: 1,
  },
  {
    name: '诊断类型：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_consultation',
    weight: 0.25,
    h: 1,
  },
  {
    name: '患者类别：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_patientCategoryName',
    weight: 0.25,
    h: 1,
  },
  {
    name: '送检医院：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_sendHospital',
    weight: 0.25,
    h: 1,
  },
  {
    name: '送检科室：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_sendDepartment',
    weight: 0.25,
    h: 1,
  },
  {
    name: '送检医生：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_sendDoctor',
    weight: 0.25,
    h: 1,
  },
  {
    name: '送检日期：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_sendDate',
    weight: 0.25,
    h: 1,
  },
  {
    name: '病区：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_wardName',
    weight: 0.25,
    h: 1,
  },
  {
    name: '病区号：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_wardId',
    weight: 0.25,
    h: 1,
  },
  {
    name: '床位号：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_bedId',
    weight: 0.25,
    h: 1,
  },
  {
    name: '医疗机构：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_service',
    weight: 0.25,
    h: 1,
  },
  {
    name: '取材部位：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_sampleBody',
    weight: 0.25,
    h: 1,
  },
  {
    name: '取材脏器：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_sampleOrgan',
    weight: 0.25,
    h: 1,
  },
  {
    name: '联系电话：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_sendDoctorTel',
    weight: 0.25,
    h: 1,
  },
  {
    name: '病理编号：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_pathologyId',
    weight: 0.25,
    h: 1,
  },
  {
    name: '标本名称：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_specimenName',
    weight: 0.25,
    h: 1,
  },
  {
    name: '标本类别：',
    smallType: 'text',
    bigType: 'base',
    i: 'text_base_specimenTypeName',
    weight: 0.25,
    h: 1,
  },
  {
    name: '报告医师（签名）：',
    smallType: 'special',
    bigType: 'base',
    i: 'special_base_reportDoctor',
    weight: 0.5,
    h: 1,
  },
];

// 常规病理组件
const defaultNormalDiagnoseComponents = [
  {
    name: '病理图像：',
    smallType: 'special',
    bigType: 'normal',
    i: 'special_normal_pathologyFiles',
    weight: 1,
    h: 3,
  },
  {
    name: '病史摘要：',
    smallType: 'text',
    bigType: 'normal',
    i: 'text_normal_summary',
    weight: 1,
    h: 3,
  },
  {
    name: '大体所见：',
    smallType: 'text',
    bigType: 'normal',
    i: 'text_normal_observed',
    weight: 1,
    h: 3,
  },
  {
    name: '镜下所见：',
    smallType: 'text',
    bigType: 'normal',
    i: 'text_normal_microFingings',
    weight: 0.5,
    h: 1,
  },
  {
    name: '清空',
    smallType: 'special',
    bigType: 'normal',
    i: 'special_clearable_microFingings',
    weight: 0.5,
    h: 1,
  },
  {
    name: '镜下所见',
    smallType: 'input',
    bigType: 'normal',
    i: 'input_normal_microFingings',
    weight: 1,
    h: 3,
  },
  {
    name: '特殊检查：',
    smallType: 'text',
    bigType: 'normal',
    i: 'text_normal_specialCheck',
    weight: 0.5,
    h: 1,
  },
  {
    name: '清空',
    smallType: 'special',
    bigType: 'normal',
    i: 'special_clearable_specialCheck',
    weight: 0.25,
    h: 1,
  },
  {
    name: '导入',
    smallType: 'special',
    bigType: 'normal',
    i: 'special_normal_import',
    weight: 0.25,
    h: 1,
  },
  {
    name: '特殊检查',
    smallType: 'input',
    bigType: 'normal',
    i: 'input_normal_specialCheck',
    weight: 1,
    h: 3,
  },
  {
    name: '病理诊断：',
    smallType: 'text',
    bigType: 'normal',
    i: 'text_normal_diagnose',
    weight: 0.5,
    h: 1,
  },
  {
    name: '清空',
    smallType: 'special',
    bigType: 'normal',
    i: 'special_clearable_diagnose',
    weight: 0.5,
    h: 1,
  },
  {
    name: '病理诊断',
    smallType: 'input',
    bigType: 'normal',
    i: 'input_normal_diagnose',
    weight: 1,
    h: 3,
  },
];
// 常规病理模块
const defaultNormalDiagnoseComponentAddList = [
  {
    name: '病理图像',
    iList: ['special_normal_pathologyFiles'],
  },
  {
    name: '病史摘要',
    iList: ['text_normal_summary'],
  },
  {
    name: '大体所见',
    iList: ['text_normal_observed'],
  },
  {
    name: '镜下所见',
    iList: [
      'text_normal_microFingings',
      'special_clearable_microFingings',
      'input_normal_microFingings',
    ],
  },
  {
    name: '特殊检查',
    iList: [
      'text_normal_specialCheck',
      'special_normal_import',
      'special_clearable_specialCheck',
      'input_normal_specialCheck',
    ],
  },
  {
    name: '病理诊断',
    iList: [
      'text_normal_diagnose',
      'special_clearable_diagnose',
      'input_normal_diagnose',
    ],
  },
];

export default {
  name: 'InstitutionReportTemplatesEdit',
  components: {
    GridLayout: VueGridLayout.GridLayout,
    GridItem: VueGridLayout.GridItem,
  },
  data() {
    const checkDeadline = (rule, value, callback) => {
      if (!value) {
        callback(new Error(' '));
        this.$message.warning('报告期限必须为正整数');
      } else {
        callback();
      }
    };
    const checkSpecimenCategory = (rule, value, callback) => {
      if (!value) {
        callback(new Error(' '));
        this.$message.warning('标本类别不能为空');
      } else {
        callback();
      }
    };
    const checkAddName = (rule, value, callback) => {
      if (!value) {
        callback(new Error(' '));
        this.$message.warning('标识名不能为空');
      } else {
        callback();
      }
    };
    const checkAddI = (rule, value, callback) => {
      if (!value) {
        this.$message.warning('标识符不能为空');
        callback(new Error(' '));
      } else {
        const flag = this.componentList.some(
          (t, index) =>
            this.componentDialog.index !== index && t.i === this.componentForm.i
        );

        if (flag) {
          this.$message.warning('标识符重复');
          callback(new Error(' '));
        } else {
          callback();
        }
      }
    };
    return {
      reportTemplateId: 0,
      isShowSign: false,
      imageServiceURL: process.env.ImageServiceURL,
      templateImageUploadUrl: `${process.env.ImageServiceURL}/upload`,
      // 默认基本信息/常规病理组件列表
      defaultBaseComponentList: defaultBaseComponents,
      defaultNormalDiagnoseComponentList: defaultNormalDiagnoseComponents,
      defaultNormalDiagnoseComponentGroup:
        defaultNormalDiagnoseComponentAddList,

      // 字典
      checkCategoryList: [],
      specimenCategoryList: [],
      dictionaryMap: [
        {
          code: 'specimenCategory',
          array: 'specimenCategoryList',
        },
      ],

      componentsCategoryActive: '',
      // 报告模板信息
      templatesInfo: {
        id: 1,

        createUserId: null,
        updateUserId: 1,
        createTime: '2019-12-02 21:49:30',
        updateTime: '2019-12-05 03:53:59',
        remark: '备注信息修改',
        isDelete: 0,
        institutionId: 1,
        checkCategory: 517,
        checkCategoryName: '常规病理',
        status: 1,
        settingsRemark: null,
        settingsDeadline: 2,
        settingsSpecimenCategory: null,
        settingsSpecimenCategoryName: null,
        settingsColNum: 12,
        infoImageUrl: null,
        infoInstitutionName: null,
        infoTitle: null,
        infoWatermark: null,
        infoRemark: '备注：',
      },
      // 组件列表
      componentList: [
        {
          id: 0,
          name: 'string',
          i: 'string',
          x: 0,
          y: 0,
          w: 4,
          h: 1,
          moved: 0,
          bigType: 'string',
          smallType: 'string',
          stringContent: 'string',
          style: '',
          styleJson: {},
          placeholder: 'string',
          isInputArea: 0,
          selectData: 'string',
          selectDataJson: [],
          selectType: 0,
        },
      ],

      // 基本设置对话框
      settingDialog: {
        visible: false,
      },
      settingForm: {
        settingsRemark: null,
        settingsDeadline: 2,
        settingsSpecimenCategory: null,
        settingsSpecimenCategoryName: null,
        settingsColNum: 12,
        checkCategory: null,
      },
      settingFormRules: {
        settingsDeadline: [vxRule(true, 'intPlus', 'blur', '请填写报告期限')],
        settingsSpecimenCategory: [
          vxRule(true, null, 'blur', '请选择标本类别'),
        ],
        checkCategory: [vxRule(true, null, 'blur', '请选择检查类别')],
      },

      // 组件新增/编辑相关
      componentDialog: {
        visible: false,
        isAddNew: true,
        index: -1,
      },
      componentBase: {
        id: 0,
        name: '',
        i: 'space_',
        x: 0,
        y: 0,
        w: 4,
        h: 1,
        moved: 0,
        bigType: 'custom',
        smallType: 'space',
        smallTypeIndex: 0,
        stringContent: '',
        style: '{}',
        styleJson: {},
        placeholder: '',
        isInputArea: 0,
        selectData: '[]',
        selectDataJson: [],
        selectType: 0,
      },
      componentForm: {},
      componentFormRules: {
        name: [
          {
            required: true,
            message: ' ',
            validator: checkAddName,
            trigger: 'blur',
          },
        ],
        i: [
          {
            required: true,
            message: ' ',
            validator: checkAddI,
            trigger: 'blur',
          },
        ],
      },
    };
  },
  mounted() {
    this.reportTemplateId = this.$store.state.reportTemplateId;
    this.dictionariesRequest(this.dictionaryMap);
    this.reportTemplateRequest();
    // this.reportTemplateComponentsRequest();
    //检查类型获取
    this.getCheckCategoryList();
  },
  computed: {
    componentsCategory() {
      const components = {
        info: [
          {
            key: 'base',
            label: '基本信息组件',
          },
          {
            key: 'normal',
            label: '常规病理组件',
          },
          {
            key: 'input',
            label: '自定义输入框组件',
          },
          {
            key: 'selection',
            label: '自定义选择框组件',
          },
          {
            key: 'text',
            label: '自定义文本组件',
          },
          {
            key: 'other',
            label: '其他组件',
          },
        ],
        base: [],
        normal: [],
        input: [],
        selection: [],
        text: [],
        other: [],
      };

      this.componentList.forEach((t, index) => {
        const item = {
          index,
          i: t.i,
          name: t.name,
        };
        switch (t.bigType) {
          case 'base':
            components.base.push(item);
            break;
          case 'normal':
            components.normal.push(item);
            break;
          case 'custom':
            switch (t.smallType) {
              case 'input':
                components.input.push(item);
                break;
              case 'selection':
                components.selection.push(item);
                break;
              case 'text':
                components.text.push(item);
                break;
              default:
                components.other.push(item);
                break;
            }
            break;
          default:
            components.other.push(item);
            break;
        }
      });

      return components;
    },
    componentFormTable() {
      const data = [];
      this.componentForm.selectDataJson.forEach((name, index) => {
        data.push({
          index,
          name,
        });
      });
      return data;
    },
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.templatesInfo.infoImageUrl = res.url;
    },
    styleString(styleJson) {
      let style = 'width: 100%; word-break:break-all;';
      Object.keys(styleJson).forEach((key) => {
        style += `${key}:${styleJson[key]};`;
      });
      return style;
    },
    async getCheckCategoryList() {
      const res = await this.$axios({
        method: 'GET',
        url: '/PROXY-Remote/dicts/by-code',
        params: {
          code: 'checkCategory',
        },
      });
      if (res && res.data.code === 200) {
        const result = res.data.data;
        this.checkCategoryList = result;
      }
    },
    // 字典数据请求
    async dictionariesRequest(dictMap) {
      dictMap.forEach(async (map) => {
        try {
          await this.$axios({
            // 详见 axios 请求配置项
            method: 'GET',
            url: '/PROXY-Remote/dicts/list',
            params: {
              code: map.code,
              page: 0,
              size: 99,
            },
          }).then((res) => {
            // 请求失败
            if (res.data.code !== 200) {
              throw new Error(res.data);
            }

            // 请求成功
            const result = res.data;
            // 查询结果数据
            result.data.forEach((t) => {
              this[map.array].push({
                id: t.id,
                name: t.name,
              });
            });
          });
        } catch (e) {
          console.log('e', e);
          // 跳出
        }
      });
    },
    // 模板数据请求
    async reportTemplateRequest() {
      try {
        await this.$axios({
          // 详见 axios 请求配置项
          method: 'GET',
          url: `/PROXY-Remote/report-templates/${this.reportTemplateId}`,
        }).then((res) => {
          // 请求失败
          if (res.data.code !== 200) {
            throw new Error(res.data);
          }

          // 请求成功
          const result = res.data.data;
          console.log(result);
          console.log(this.templatesInfo, result);
          Object.keys(this.templatesInfo).forEach((key) => {
            this.templatesInfo[key] = result[key];
          });
          this.componentList = [];
          result.reportTemplateComponents.forEach((t, index) => {
            const item = t;
            item.index = index;
            if (t.smallType === 'input' || t.smallType === 'selection') {
              item.value = '';
            }
            this.componentList.push(item);
          });
        });
      } catch (e) {
        console.log('e', e);
        // 跳出
      }
    },
    // 保存请求
    async reportTemplateSaveRequest() {
      const template = this.templatesInfo;
      template.reportTemplateComponents = [];
      this.componentList.forEach((t) => {
        const item = t;
        item.moved = 0;

        item.style = JSON.stringify(t.styleJson);
        delete item.styleJson;
        if (!item.style) {
          item.style = '{}';
        } else {
          item.style = item.style.replace(/"/g, "'");
        }

        item.selectData = JSON.stringify(t.selectDataJson);
        delete item.selectDataJson;
        if (!item.selectData) {
          item.selectData = '{}';
        } else {
          item.selectData = item.selectData.replace(/"/g, "'");
        }
        template.reportTemplateComponents.push(item);
      });
      try {
        await this.$axios({
          // 详见 axios 请求配置项
          method: 'POST',
          url: '/PROXY-Remote/report-templates',
          data: template,
          headers: {
            'Content-Type': 'application/json',
          },
        }).then((res) => {
          // 请求失败
          if (res.data.code !== 200) {
            console.error('e', res.data);
            throw new Error(res.data);
          }
          this.$router.push('/institution/report-templates');
          // 请求成功
          this.$message.success('保存成功');
        });
      } catch (e) {
        console.log('e', e);
        // 跳出
      }
    },
    // 保存
    templateSave() {
      this.reportTemplateSaveRequest();
    },
    // 恢复
    templateRecover() {
      this.reportTemplateRequest();
    },
    // 预览
    templatePreview() {
      this.$store.commit('setPropertyGeneral', {
        key: 'reportTemplateId',
        value: this.reportTemplateId,
      });
      this.$router.push('/report-templates/preview/' + this.reportTemplateId);
      //window.open('/report-templates/preview');
    },
    // TODO：默认
    templateDefault() {
      console.log('templateDefault');
    },

    // 组件新增与编辑
    componentDialogOpen(index) {
      this.componentForm = _.clone(this.componentBase);
      if (index < 0) {
        this.componentDialog.isAddNew = true;
        this.componentDialog.title = '新增组件';
        delete this.componentDialog.id;
      } else {
        this.componentDialog.isAddNew = false;
        this.componentDialog.title = '编辑组件';
        Object.keys(this.componentForm).forEach((key) => {
          this.componentForm[key] = _.clone(this.componentList[index][key]);
        });
      }

      this.componentDialog.index = index;
      this.componentDialog.visible = true;
    },
    componentDialogSubmit() {
      this.$refs.componentForm.validate((valid) => {
        if (valid) {
          if (this.componentDialog.isAddNew) {
            if (this.componentForm.bigType === 'normal') {
              const baseNormal = _.clone(this.componentForm);
              const { smallTypeIndex } = baseNormal;
              this.defaultNormalDiagnoseComponentGroup[
                smallTypeIndex
              ].iList.forEach((i) => {
                const normal = this.defaultNormalDiagnoseComponentList.find(
                  (t) => t.i === i
                );

                baseNormal.i = normal.i;
                baseNormal.name = normal.name;
                baseNormal.h = normal.h;
                baseNormal.w = parseInt(
                  normal.weight * this.templatesInfo.settingsColNum,
                  10
                );
                baseNormal.smallType = normal.smallType;

                baseNormal.stringContent = normal.name;
                baseNormal.styleJson = {
                  'text-align': 'left',
                };
                baseNormal.placeholder = `请输入${normal.name}`;
                baseNormal.isInputArea = normal.h > 1 ? 1 : 0;
                baseNormal.selectData = '';
                baseNormal.selectType = 0;
                this.componentAddNew(baseNormal);
              });
              this.$message.success('新增组件成功');
              this.componentDialog.visible = false;
            } else {
              this.componentAddNew(this.componentForm);
              this.$message.success('新增组件成功');
              this.componentDialog.visible = false;
            }
          } else {
            const component = _.clone(this.componentForm);
            component.style = JSON.stringify(component.styleJson);
            component.selectData = JSON.stringify(component.selectDataJson);

            this.componentList[this.componentDialog.index] = _.clone(component);
            this.$message.success('编辑成功');
            this.componentDialog.visible = false;
          }
        }
      });
    },
    // 大类型切换，表单重置
    componentFormBigTypeChanged() {
      this.componentForm.smallType = 'space';
      this.componentFormSmallTypeChanged('space');
      this.componentForm.smallTypeIndex = 0;
      this.componentFormSmallTypeIndexChanged(0);
    },
    componentFormSmallTypeIndexChanged(index) {
      const { bigType } = this.componentForm;
      let baseItem = null;
      let normalGroup = null;
      switch (bigType) {
        case 'base':
          baseItem = this.defaultBaseComponentList[index];
          this.componentForm.i = baseItem.i;
          this.componentForm.name = baseItem.name;
          this.componentForm.h = baseItem.h;
          this.componentForm.w = parseInt(
            baseItem.weight * this.templatesInfo.settingsColNum,
            10
          );
          this.componentForm.smallType = baseItem.smallType;

          this.componentForm.stringContent = baseItem.name;
          this.componentForm.styleJson = {
            'text-align': 'left',
          };
          this.componentForm.placeholder = '';
          this.componentForm.isInputArea = 0;
          this.componentForm.selectData = '';
          this.componentForm.selectType = 0;
          break;
        case 'normal':
          normalGroup = this.defaultNormalDiagnoseComponentGroup[index];
          [this.componentForm.i] = normalGroup.iList;
          this.componentForm.name = normalGroup.name;
          break;
        default:
          break;
      }
    },
    componentFormSmallTypeChanged(val) {
      if (this.componentForm.bigType === 'custom') {
        this.componentForm.i = `${val}_`;
        this.componentForm.name = '';

        this.componentForm.stringContent = '';
        this.componentForm.styleJson = {
          'text-align': 'left',
        };
        this.componentForm.placeholder = '';
        this.componentForm.isInputArea = 0;
        this.componentForm.selectData = '';
        this.componentForm.selectType = 0;
      }
    },
    // 自定义选择框新增选项
    componentFormSelectionAdd() {
      this.$prompt('请输入新选择项名称', '选择项新增', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.*[^\s]/,
        inputErrorMessage: '选择项名称不能为空',
      }).then((box) => {
        const flag = this.componentForm.selectDataJson.some(
          (t) => t === box.value
        );
        if (flag) {
          this.$message.warning('选择项重复');
        } else {
          this.componentForm.selectDataJson.push(box.value);
          this.$message.success('选择项新增成功');
        }
      });
    },
    componentFormTableEdit(item) {
      this.$prompt('请输入选择项新名称', '选择项更新', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: item.name,
        inputPattern: /.*[^\s]/,
        inputErrorMessage: '选择项新名称不能为空',
      }).then((box) => {
        const array = this.componentForm.selectDataJson;
        const flag = array.some(
          (t, index) => t === box.value && index !== item.index
        );
        if (flag) {
          this.$message.warning('选择项名称重复');
        } else {
          this.componentForm.selectDataJson.splice(item.index, 1, box.value);
          this.$message.success('选择项名称更新成功');
        }
      });
    },
    componentFormTableRemove(index) {
      this.componentForm.selectDataJson.splice(index, 1);
    },
    componentAddNew(newComponent) {
      const that = this;
      const componentAddNew = function (componentBase) {
        const component = _.clone(componentBase);
        delete component.id;
        component.style = JSON.stringify(component.styleJson);
        component.selectData = JSON.stringify(component.selectDataJson);

        let posY = 1;
        that.componentList.forEach((t) => {
          posY = Math.max(posY, t.y + t.h);
        });
        component.y = posY;
        that.componentList.push(component);
      };

      componentAddNew(newComponent);
    },

    // 模板基础设置
    settingDialogOpen() {
      Object.keys(this.settingForm).forEach((key) => {
        this.settingForm[key] = this.templatesInfo[key];
      });
      this.settingDialog.visible = true;
    },
    validateForm() {
      let decide = false;
      this.$refs.settingForm.validate((valid) => {
        if (valid) {
          decide = true;
        } else {
          this.activeName = 'basicInformation';
        }
      });
      return decide;
    },
    async settingDialogSave() {
      if (!this.validateForm()) {
        return;
      }
      Object.keys(this.settingForm).forEach((key) => {
        this.templatesInfo[key] = this.settingForm[key];
      });
      this.settingDialog.visible = false;
      this.$message.success('保存成功');
    },
    // 复制功能
    async componentClone(index) {
      const item = this.componentList[index];
      let flag = false;
      if (item.bigType === 'base' || item.bigType === 'normal') {
        const msg =
          '基本信息组件或常规病理组件具有特殊功能性，不建议复制该组件，是否继续？';
        await this.$confirm(msg, '组件复制提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          flag = true;
        });
      } else {
        flag = true;
      }

      if (flag) {
        const isCopy = item.i.match(/_[0-9]+$/);
        const currentID = isCopy ? item.i.split(isCopy.pop())[0] : item.i;
        console.log('currentID', currentID, isCopy);

        let num = 1;
        for (;;) {
          const tempID = `${currentID}_${num}`;
          if (this.componentList.some((t) => t.i === tempID)) {
            num++;
          } else {
            const component = _.clone(item);
            delete component.id;

            component.i = tempID;
            component.x = 0;
            component.y = 0;
            component.w = 4;
            component.h = 1;

            console.log('componentAddCommit', item, component, tempID);
            this.componentAddNew(component);
            this.$message.success('复制成功');
            break;
          }
        }
      }
    },
    componentRemove(index) {
      this.componentList.splice(index, 1);
    },
  },
};
</script>

<style scoped>
.row-in-grid-item {
  min-height: 28px;

  display: flex;

  align-items: center;
}

.container-inner {
  margin: 0 auto;

  width: max-content;
}

.container-left {
  float: left;

  margin-right: 20px;

  width: 400px;

  background: #ffffff;

  padding: 20px 20px;
}

.container-right {
  float: left;

  margin-left: 20px;

  width: 800px;

  background: #ffffff;

  padding: 20px;
}

.radio-group {
  padding: 10px 0 0 0;

  line-height: 24px;
}
.row-padding-bottom {
  padding-bottom: 10px;
}
</style>
